<script setup>
import {onMounted, reactive} from "vue";
import {deleteLogBatchService, getLogListService} from "@/api/log.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  username: "",
  operation: "",
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  selectedRows: [],
});

// 获取日志列表
const LogList = async () => {
  const res = await getLogListService({
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    username: data.username,
    operation: data.operation,
  });
  if (res.data.code === '200') {
    data.tableData = res.data.data.list;
    data.total = res.data.data.total;
  } else {
    ElMessage.error("获取日志失败");
  }
};

// 表格行数据
const handleSelectionChange = (val) => {
  data.selectedRows = val
}

onMounted(async () => {
  await LogList();
})

// 重置
const refresh = () => {
  data.username = "";
  data.operation = "";
  LogList();
};

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  data.pageSize = newSize;
  LogList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  data.pageNum = newPage;
  LogList();
};
const handleLogDeleteBatch = async () => {
  if (!data.selectedRows || data.selectedRows.length === 0) {
    ElMessage.warning("请先选择要删除的日志");
    return;
  }
  const ids = data.selectedRows.map(item => item.id)
  ElMessageBox.confirm(
      '当前操作将永久删除选中的日志，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteLogBatchService(ids)
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await LogList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    ArticleList()
    ElMessage.info('取消删除');
  });
}
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};
</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="data.username" clearable style="width: 240px; margin-right: 20px" placeholder="请输入用户名"/>
      <el-input v-model="data.operation" clearable style="width: 240px" placeholder="请输入请求方式"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="LogList">查询</el-button>
      <el-button type="warning" icon="Refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container" style="margin-top: 20px">
      <el-button type="danger" style="margin-left: 0" icon="Delete"
                 @click="handleLogDeleteBatch">批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="data.tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column prop="username" align="center" label="用户名" width="180"/>
        <el-table-column prop="operation" align="center" label="操作描述" width="180"/>
        <el-table-column prop="requestUrl" align="center" label="请求地址"/>
        <el-table-column align="center" label="请求方式" width="100">
          <template #default="scope">
            <el-text v-if="scope.row.requestMethod === 'DELETE'" type="danger">{{ scope.row.requestMethod }}</el-text>
            <el-text v-if="scope.row.requestMethod === 'POST'" type="success">{{ scope.row.requestMethod }}</el-text>
            <el-text v-if="scope.row.requestMethod === 'PUT'" type="info">{{ scope.row.requestMethod }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="time" align="center" label="耗时(ms)" width="100"/>
        <el-table-column prop="status" align="center" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="操作时间" width="250">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<style scoped lang="scss">
.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}
</style>
